const path = require("path");
const fs = require("fs-extra"); // fs 的一个扩展

module.exports = async (context) => {
    // 删除不必要的语言包，只保留中文
    const localesDir = path.join(context.appOutDir, "locales");
    if (await fs.pathExists(localesDir)) {
        const files = await fs.readdir(localesDir);
        for (const file of files) {
            if (!file.endsWith("zh-CN.pak") && !file.endsWith("en-US.pak")) {
                await fs.remove(path.join(localesDir, file));
            }
        }
    }

    // 删除不必要的文件
    const filesToDelete = [
        "LICENSE.electron.txt",
        "LICENSES.chromium.html",
        "LICENSE",
        "version"
    ];

    for (const fileName of filesToDelete) {
        const filePath = path.join(context.appOutDir, fileName);
        if (await fs.pathExists(filePath)) {
            await fs.remove(filePath);
        }
    }

    // 删除不必要的资源文件，但保留 dist 和 public 目录
    const resourcesDir = path.join(context.appOutDir, "resources");
    if (await fs.pathExists(resourcesDir)) {
        // 删除不必要的图标和资源，但保留用户需要的静态资源
        const unnecessaryFiles = [
            "app.asar.unpacked",
            "electron.asar"
        ];
        
        for (const file of unnecessaryFiles) {
            const filePath = path.join(resourcesDir, file);
            if (await fs.pathExists(filePath)) {
                await fs.remove(filePath);
            }
        }
        
        // 确保 dist、public 目录和配置文件存在且不被删除
        const keepDirs = ["dist", "public"];
        for (const dir of keepDirs) {
            const dirPath = path.join(resourcesDir, dir);
            if (!(await fs.pathExists(dirPath))) {
                console.log(`创建必要目录: ${dir}`);
                await fs.ensureDir(dirPath);
            }
        }
        
        // 确保配置文件存在
        const configFiles = ["config.json", "config-duty.json", "config-dispatch.json", "config-weather.json"];
        for (const configFile of configFiles) {
            const configPath = path.join(resourcesDir, configFile);
            if (!(await fs.pathExists(configPath))) {
                console.log(`配置文件不存在: ${configPath}`);
            } else {
                console.log(`配置文件已保留: ${configPath}`);
            }
        }
    }

    // 删除调试文件
    const debugFiles = [
        "chrome_100_percent.pak",
        "chrome_200_percent.pak",
        "resources.pak"
    ];

    for (const fileName of debugFiles) {
        const filePath = path.join(context.appOutDir, fileName);
        if (await fs.pathExists(filePath)) {
            await fs.remove(filePath);
        }
    }
};